const express = require('express')
const expressWs = require('express-ws')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
const cors = require('cors')
const fileUpload = require('express-fileupload')
const router = require('./routes')
const Config = require('./config')
const logger = require('./utils/log4js')
const ws = require('./ws')

const app = express()
expressWs(app)
ws(app)

app.use(cors())
app.use(fileUpload({}))
app.use(express.static('public'))
app.all('*', (req, res, next) => {
	res.header('Access-Control-Allow-Origin', '*')
	res.header('Access-Control-Allow-Headers', 'content-type')
	res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
	res.header('Content-Type', 'application/json;charset=utf-8')
	next()
})

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.use('/', router)

app.listen(Config.sys.port, async () => {
	await mongoose.connect(`mongodb://${Config.db.host}:${Config.db.port}/${Config.db.db}`)
	logger.info('listenPort:', Config.sys.port)
})
